package service

import (
	"errors"
)

var SynHub *Hub

type Hub struct {
	ReqData map[string]interface{}
	Receive chan interface{}
	Request chan *Hub
}

func HubInit() {
	SynHub = newHub()
	go SynHub.start()
}
func newHub() *Hub {
	return &Hub{
		ReqData: make(map[string]interface{}),
		Receive: make(chan interface{}, 1),
		Request: make(chan *Hub),
	}
}

func (h *Hub) start() {
	for {
		select {
		case data := <-h.Request:
			addr, ok := data.ReqData["addr"].(string)
			if !ok {
				break
			}
			msg, ok := data.ReqData["msg"].([]byte)
			if !ok {
				break
			}
			client, err := NewTCPClient(addr)
			if err != nil {
				data.Receive <- err
				break
			}
			b, err := client.RequestData(msg)
			client.Close()
			if err != nil {
				data.Receive <- err
			} else {
				data.Receive <- b
			}
		}
	}
}

func (h *Hub) SendStrData(add string, data string) (string, error) {
	var resp string
	var err error
	req := newHub()
	req.ReqData = map[string]interface{}{
		"addr": add,
		"msg":  []byte(data),
	}
	SynHub.Request <- req
	result := <-req.Receive
	switch result.(type) {
	case error:
		err = result.(error)
	case []byte:
		resp = string(result.([]byte))
	default:
		err = errors.New("unknown type")
	}
	return resp, err
}
